<template>
  <base-breadcrumb v-loading="loading" :isAudit="isAudit">
    <div class="about-master-container">
      <a-card>
        <title-name title="基本信息"></title-name>
        <BForm
          ref="BForm"
          :config="formConfig"
          :form="form"
          :rule="rules"
          @selectOrg="selectOrg"
        />
      </a-card>

      <a-card>
        <title-name title="项目安全生产风险评价表"></title-name>
        <a-table
          :pagination="false"
          :columns="columns"
          :data-source="form.headList"
          bordered
        >
          <template slot="check" slot-scope="text, record">
            <a-checkbox v-model="record.existence" @change="calc(record,1)" :disabled="disabled" />
            是
            <a-checkbox v-model="record.existence2" @change="calc(record,2)" :disabled="disabled" style="margin-left: 40px;" />
            否
          </template>
          <template slot="content" slot-scope="text, record">
            <b-input v-model="record.content" @blur="calc" :disabled="disabled" />
          </template>
        </a-table>
        <div class="flex align-items-center mt20">
          风控类型：
          <BSelect v-model="form.riskTypeId" :list="riskTypeList" :keys="['value','label']" disabled />
        </div>
      </a-card>

      <div class="tar page-btn-right-top">
        <template v-if="!disabled">
          <a-button type="primary" @click="save(form.auditStatus)" class="mr20">保存</a-button>
          <a-button v-if="form.auditStatus !== 'PAST'" type="primary" @click="submit('SUBMITTED')" class="mr20">提交
          </a-button>
        </template>
        <a-button v-checkVisibleInDetail @click="$close">关闭</a-button>
      </div>
    </div>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>
<script>
import rectifyNoticeApi from '@/api/safetySupervision/checkAndRectify/rectifyNotice'
import SelectSubCompany from '@/components/Select/SelectSubCompany'
import SelectProject from '@/components/Select/SelectProject'
import { getProjectsDel } from '@/api/project/projects'
import Api from '@/api/safetySupervision/hazardIdentification/riskProjectControl'

export default {
  name: 'edit',
  components: {},
  props: {
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.disabled = true
        }
      }
    }
  },
  data() {
    return {
      columns: [
        {
          title: '部门/事项', dataIndex: 'parentName', width: 200,
          customRender: (text, row, index) => {
            //大体逻辑，在数组中第一条和最后一条的下标不同，那么就是有多条的，反之
            let lastIndex = -1
            this.form.headList.map((v, i) => {
              if (v.parentName === text) {
                lastIndex = i
              }
            })
            let firstIndex = this.form.headList.findIndex(v => v.parentName === text)
            let obj = { children: text, attrs: { rowSpan: 1 } }
            if (index === 0) {
              obj.attrs.rowSpan = lastIndex === firstIndex ? 1 : (lastIndex + 1) - firstIndex
            } else {
              // 若该行考核内容和上一行一致，则使其隐藏
              if (this.form.headList[index - 1].parentName === text) {
                obj.attrs.rowSpan = 0
                // 若不是，则往下合并与改行内容一致行的总行数
              } else {
                obj.attrs.rowSpan = lastIndex === firstIndex ? 1 : (lastIndex + 1) - firstIndex
              }
            }
            return obj
          }
        },
        { title: '风险指标', dataIndex: 'name' },
        { title: '是否存在', width: 180, scopedSlots: { customRender: 'check' } },
        { title: '备注', dataIndex: 'content', width: 300, scopedSlots: { customRender: 'content' } }
      ],
      loading: false,
      form: {
        id: null,
        riskTypeId: '',
        auditStatus: 'DRAFT',
        headList: []
      },
      rules: {
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }]
      },
      riskTypeList: [
        { value: '758219883677880323', label: '非风险项目' },
        { value: '758219883677880322', label: '局控风险项目' },
        { value: '758219883677880321', label: '公司控风险项目' }
      ],
      disabled: this.$route.query.pageType === 'look',
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    formConfig() {
      return [
        {
          row: true,
          children: [
            {
              label: '所属单位',
              type: 'orgTree',
              keyName: 'projectId',
              rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
              span: 24,
              isAutoSelectFirst: !this.disabled,
              isNeedAuth:true,
              checkStrictly: true,
              disabled: this.disabled,
              isQueryProjecDetail: false
            },
            // {
            //   type: SelectSubCompany,
            //   value: 'branchComId',
            //   label: '分公司',
            //   attrs: {
            //     autoSelected: true,
            //     disabled: true
            //   },
            //   on: {
            //     selectChange: e => this.form.branchComName = e.orgName
            //   },
            //   show: !this.disabled
            // },
            // {
            //   type: SelectProject,
            //   value: 'projectId',
            //   label: '项目',
            //   colSpan: 16,
            //   attrs: {
            //     autoSelected: false,
            //     isEdit: this.form.id !== null,
            //     form: this.form,
            //     keyValue: 'branchComId'
            //   },
            //   on: {
            //     selectChange: async e => {
            //       if (e) {
            //         this.form.projectName = e.name
            //         this.loading = true
            //         let res = await getProjectsDel({ projectId: e.code })
            //         this.loading = false
            //         this.form.oneAreaName = res.data.oneAreaName
            //         this.form.secondAreaName = res.data.secondAreaName
            //         this.form.threeAreaName = res.data.threeAreaName
            //       }
            //     }
            //   },
            //   show: !this.disabled
            // },
            // { type: 'input', value: 'branchComName', label: '分公司', attrs: { disabled: true }, show: this.disabled },
            // {
            //   type: 'input', value: 'projectName', label: '项目', colSpan: 16,
            //   attrs: { disabled: true }, show: this.disabled
            // },
            { type: 'input', value: 'oneAreaName', label: '一级地域', attrs: { disabled: true } },
            { type: 'input', value: 'secondAreaName', label: '二级地域', attrs: { disabled: true } },
            { type: 'input', value: 'threeAreaName', label: '三级地域', attrs: { disabled: true } }
          ]
        }
      ]
    }
  },
 async created() {
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id
      this.getData()
    } else {
      this.getTreeTableList()
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('risk_project_grade_control')
  },
  methods: {
   async selectOrg(val) {
        this.form.branchComName = val[val.length - 2].orgName
        this.form.branchComId = val[val.length - 2].orgId
       this.form.projectName = val[val.length - 1].projectName
       this.form.projectId = val[val.length - 1].projectId
       this.loading = true
       let res = await getProjectsDel({ projectId:  this.form.projectId })
       this.loading = false
       this.form.oneAreaName = res.data.oneAreaName
       this.form.secondAreaName = res.data.secondAreaName
       this.form.threeAreaName = res.data.threeAreaName

    },
    async getTreeTableList(list) {
      if (!list) {
        let res = await Api.getRiskTemplate()
        if (res.code === this.SUCCESS_CODE) {
          list = res.data
        }
      }
      let tempTreeTableList = []
      list.map(v => {
        if (v.itemList) {
          let temp = []
          v.itemList.map(w => {
            w.parentName = v.name
            if (this.form.id === null) {
              w.existence = null
              w.existence2 = null
            } else {
              if (w.existence!==null){
                w.existence2 = !w.existence
              }else {
                w.existence2 = null
              }
            }
            temp.push(w)
          })
          tempTreeTableList = tempTreeTableList.concat(temp)
        }
      })
      this.form.headList = this.$clone(tempTreeTableList)
      this.calc()
    },
    calc(row, type) {
      if (row){
        if (row.existence === true && type === 1) {
          row.existence2 = false
        }
        if (row.existence2 === true && type === 2) {
          row.existence = false
        }
      }

      let res = this.form.headList.filter(v => v.existence)
      if (res) {
        if (res.length < 3) this.form.riskTypeId = this.riskTypeList.find(v => v.label === '非风险项目').value
        if (res.length >= 3 && res.length < 5) this.form.riskTypeId = this.riskTypeList.find(v => v.label === '公司控风险项目').value
        if (res.length >= 5) this.form.riskTypeId = this.riskTypeList.find(v => v.label === '局控风险项目').value
      }
    },
    async getData() {
      this.loading = true
      let res = await Api.findListByMainId({}, { id: this.form.id })
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        this.form = res.data
        this.getTreeTableList(this.form.headList)
      }
    },
    async checkValidate() {
      return new Promise(resolve => {
        this.$refs.BForm.validate((valid) => {
          resolve(valid)
        })
      })
    },
    async submit(status) {
      if (await this.checkValidate()) {
        await this.save(status)
      }
    },
    async save(status) {
      this.setProcessConfig = null;
      let temp = this.$clone(this.form)
      temp.auditStatus = status
      let tempHeadList = []
      temp.headList.map(v => {
        let resIndex = tempHeadList.findIndex(w => w.name === v.parentName)
        if (resIndex === -1) {
          let item = { ...v, itemList: [v] }
          item.name = item.parentName
          tempHeadList.push(item)
        } else {
          tempHeadList[resIndex].itemList.push(v)
        }
      })
      temp.headList = tempHeadList
      let res
      this.loading = true
      this.submitApprovalConfirm(status =='SUBMITTED' ? this.processConfig : 6, async (flag)=>{
        if(!flag) {
          this.loading = false
          return
        }
        if (temp.id) {
          res = await Api.editByMain(temp)
        } else {
          res = await Api.createByMain(temp)
        }
        this.loading = false
        if (res.code === this.SUCCESS_CODE) {
          this.$noticeSuccess('操作成功')
          if(status =='SUBMITTED') {
            //提交时，返回id
            this.businessId = res.data.id;
            this.setProcessConfig = this.processConfig;
            return
          }else{
            this.$close()
          }
        }
      })

    }
  }
}
</script>
<style>
.ant-select-arrow-icon {
  display: none !important;
}
</style>
